package com.weijian.service.impl;

import com.weijian.common.pojo.CommonResult;
import com.weijian.dal.entity.Item;
import com.weijian.dal.entity.Order;
import com.weijian.dal.entity.SetMeal;
import com.weijian.dal.entity.User;
import com.weijian.dal.enums.OrderStatus;
import com.weijian.dal.vo.BusinessDataVO;
import com.weijian.dal.vo.DishOverViewVO;
import com.weijian.dal.vo.OrderOverViewVO;
import com.weijian.dal.vo.SetmealOverViewVO;
import com.weijian.mapper.OrderMapper;
import com.weijian.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class WorkspaceServiceImpl implements WorkspaceService {

    final OrderService orderService;

    final UserService userService;

    final ItemService itemService;

    final SetMealService setMealService;

    final OrderMapper orderMapper;

    public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {
        /**
         * 营业额：当日已完成订单的总金额
         * 有效订单：当日已完成订单的数量
         * 订单完成率：有效订单数 / 总订单数
         * 平均客单价：营业额 / 有效订单数
         * 新增用户：当日新增用户的数量
         */

        //查询总订单数
        Long totalOrderCount = orderService.lambdaQuery()
                .between(Order::getPayTime, begin, end)
                .count();

        //营业额
        Double turnover = orderService.lambdaQuery().select(Order::getTotalFee)
                .between(Order::getPayTime, begin, end)
                .eq(Order::getStatus, OrderStatus.COMPLETED.value).list()
                .stream()
                .mapToDouble(Order::getTotalFee)
                .sum();
        //有效订单数
        Long validOrderCount = orderService.lambdaQuery()
                .between(Order::getPayTime, begin, end)
                .eq(Order::getStatus, OrderStatus.COMPLETED.value)
                .count();

        double unitPrice = 0.0;
        double orderCompletionRate = 0.0;
        if (totalOrderCount != 0 && validOrderCount != 0) {
            //订单完成率
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
            //平均客单价
            unitPrice = turnover / validOrderCount;
        }
        //新增用户数
        Long newUsers = userService.lambdaQuery()
                .between(User::getCreateTime, begin, end)
                .count();
        return BusinessDataVO.builder()
                .turnover(turnover)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .unitPrice(unitPrice)
                .newUsers(newUsers)
                .build();
    }

    public OrderOverViewVO getOrderOverView() {
        Map<Integer, Long> map = null;
        try {
            List<Map<String, Object>> result = orderMapper.countOrdersByStatus();
            if (result != null) {
                map = result.stream()
                        .collect(Collectors.toMap(
                                m -> ((Number) m.get("status")).intValue(),
                                m -> ((Number) m.get("count")).longValue()
                        ));
            }
        } catch (Exception e) {
            log.error("统计订单失败", e);
            throw new RuntimeException(e);
        }
        return OrderOverViewVO.builder()
                .waitingOrders(map.get(1))
                .deliveredOrders(map.get(2))
                .cancelledOrders(map.get(3))
                .completedOrders(map.get(4))
                .allOrders(orderService.lambdaQuery().ne(Order::getStatus, 0).count())
                .build();
    }

    @Override
    public CommonResult<DishOverViewVO> getDishOverView() {
        Long countEnable = itemService.lambdaQuery()
                .eq(Item::getStatus, 1)
                .count();
        Long countDisable = itemService.lambdaQuery()
                .eq(Item::getStatus, 0)
                .count();
        return CommonResult.success(DishOverViewVO.builder()
                .sold(countEnable)
                .discontinued(countDisable)
                .build());
    }

    @Override
    public CommonResult<SetmealOverViewVO> getSetMealOverView() {
        Long countEnable = setMealService.lambdaQuery()
                .eq(SetMeal::getStatus, 1)
                .count();
        Long countDisable = setMealService.lambdaQuery()
                .eq(SetMeal::getStatus, 0)
                .count();
        return CommonResult.success(SetmealOverViewVO.builder()
                .sold(countEnable)
                .discontinued(countDisable)
                .build());
    }

}
